<template>
  <div class="app-container">
    <div class="filter-container">
      <el-date-picker
        v-model="times"
        class="filter-item"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 250px;"
        type="daterange"
        value-format="yyyy-MM-dd"
      />
      <el-select
        v-model="listQuery.channelId"
        filterable
        clearable
        :filter-method="appdataFilter"
        placeholder="选择应用名称"
        style="width: 150px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      >
        <el-option
          v-for="(item, index) in authChanneloptions"
          :key="index"
          :label="item.authChannelName"
          :value="item.authChannelId"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
    </div>
    <el-table
      :data="authData"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column prop="id" label="编号" align="center" width="60">
      </el-table-column>
      <el-table-column
        prop="channelCode"
        label="渠道标识"
        align="center"
        width="80"
      >
      </el-table-column>
      <el-table-column prop="authChannelName" label="渠道名" align="center">
      </el-table-column>
      <el-table-column prop="model" label="对接模式" width="120" align="center">
      </el-table-column>
      <el-table-column prop="collisionNum" label="撞库量" align="center">
      </el-table-column>
      <el-table-column prop="returnUrlNum" label="返回url数量" align="center">
      </el-table-column>
      <el-table-column
        prop="insuranceCommitNum"
        label="机构确认数"
        align="center"
      >
      </el-table-column>
      <el-table-column min-width="100" align="center">
        <template slot="header">
          <span>进件数</span>
          <el-popover
            placement="top"
            width="200"
            trigger="hover"
            content="不包含手推"
          >
            <i class="el-icon-info" slot="reference"></i>
          </el-popover>
        </template>
        <template slot-scope="{ row }">
          <span>{{ row.insuranceSuccessNum }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="priceMode" label="计费模式" align="center">
      </el-table-column>
      <el-table-column prop="price" label="价格" align="center">
      </el-table-column>
      <el-table-column
        prop="insurancePercent"
        label="机构进件率"
        align="center"
      >
      </el-table-column>

      <el-table-column
        prop="channelSettlementNum"
        label="渠道结算量"
        align="center"
      >
      </el-table-column>
      <el-table-column min-width="100" align="center">
        <template slot="header">
          <span>机构进件量</span>
          <el-popover
            placement="top"
            width="200"
            trigger="hover"
            content="包含手推"
          >
            <i class="el-icon-info" slot="reference"></i>
          </el-popover>
        </template>
        <template slot-scope="{ row }">
          <span>{{ row.insuranceApplyNum }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="apsapplyNum"
        label="APS推送量"
        align="center"
        min-width="80"
      >
      </el-table-column>
      <el-table-column
        prop="appUV"
        label="贷超唯一访问量"
        align="center"
        min-width="80"
      >
      </el-table-column>
      <el-table-column label="成本消耗" align="center" min-width="100">
        <template slot-scope="scope">
          <el-button type="text">{{
            CalculateConsumArr[scope.$index]
          }}</el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column label="成本消耗" align="center" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="showCalculateConsumption(scope)">{{
            CalculateConsumArr[scope.$index]
          }}</el-button>
        </template>
      </el-table-column> -->
      <el-table-column label="预估营收" align="center" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="showEstimatedrevenue(scope)">{{
            EstimatedrevenueArr[scope.$index]
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="预估ROI" align="center" width="100">
        <template slot-scope="scope">
          {{
            ['NaN', 'Infinity'].includes(
              roundNumber(
                (EstimatedrevenueArr[scope.$index] -
                  CalculateConsumArr[scope.$index]) /
                  CalculateConsumArr[scope.$index],
                3
              )
            )
              ? '-'
              : roundNumber(
                  (EstimatedrevenueArr[scope.$index] -
                    CalculateConsumArr[scope.$index]) /
                    CalculateConsumArr[scope.$index],
                  3
                )
          }}
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getAuthStatistics"
    />

    <!-- 计算消耗金额 -->
    <el-dialog
      title="计算消耗金额"
      :visible.sync="CalculateConsumptionForm"
      :close-on-click-modal="false"
    >
      <el-form :model="Consumption">
        <el-form-item label="渠道单价" :label-width="formLabelWidth">
          <template slot-scope="scope">
            <el-input
              v-model="Consumption.amount"
              @input="CalculateConsum(scope)"
              style="width: 200px;"
            ></el-input>
          </template>
        </el-form-item>
        <el-form-item label="授权量" :label-width="formLabelWidth">
          <el-input
            v-model="Consumption.insuranceApplyNum"
            autocomplete="off"
            @input="CalculateConsum($event)"
            style="width: 200px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="消耗金额" :label-width="formLabelWidth">
          <el-input
            v-model="Consumption.amountSum"
            autocomplete="off"
            style="width: 200px;"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="CalculateConsumptionForm = false">取 消</el-button>
        <el-button type="primary" @click="CalculateConsumptionForm = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 计算预估营收 -->
    <el-dialog
      title="预估营收"
      center
      :visible.sync="CalculateEstimatedrevenueForm"
      :close-on-click-modal="false"
    >
      <el-form :model="Estimatedrevenue">
        <div class="demo-input-suffix">
          <div class="Calculate_name">
            机构：{{
              Estimatedrevenue.insuranceApplyNum * Estimatedrevenue.AvgIncome
            }}元
          </div>
          <el-form-item label="进件量:" :label-width="formLabelWidth">
            <template slot-scope="scope">
              <el-col :span="6">
                <el-input
                  v-model="Estimatedrevenue.insuranceApplyNum"
                  @input="CalculateEstimatedRevenue(scope)"
                  style="width: 80%;"
                  autocomplete="off"
                ></el-input>
              </el-col>
              <el-col
                class="line"
                :span="2"
                style="font-weight: bolder;margin-left: 20px;"
              >
                平均单价:
              </el-col>
              <el-col :span="6">
                <el-input
                  v-model="Estimatedrevenue.AvgIncome"
                  autocomplete="off"
                  style="width: 80%;"
                  @input="CalculateEstimatedRevenue(scope)"
                ></el-input>
              </el-col>
            </template>
          </el-form-item>
        </div>
        <div class="demo-input-suffix">
          <div class="Calculate_name">
            APS：{{
              Estimatedrevenue.apsapplyNum * Estimatedrevenue.APSPushIncome
            }}元
          </div>
          <el-form-item label="推送量:" :label-width="formLabelWidth">
            <template slot-scope="scope">
              <el-col :span="6">
                <el-input
                  v-model="Estimatedrevenue.apsapplyNum"
                  autocomplete="off"
                  style="width: 80%;"
                  @input="CalculateEstimatedRevenue(scope)"
                ></el-input>
              </el-col>
              <el-col
                class="line"
                :span="2"
                style="font-weight: bolder;margin-left: 20px;"
              >
                平均单价:
              </el-col>
              <el-col :span="6">
                <el-input
                  v-model="Estimatedrevenue.APSPushIncome"
                  autocomplete="off"
                  style="width: 80%;"
                  @input="CalculateEstimatedRevenue(scope)"
                ></el-input>
              </el-col>
            </template>
          </el-form-item>
        </div>

        <div class="demo-input-suffix">
          <div class="Calculate_name">
            贷超：{{
              Estimatedrevenue.APPUV * Estimatedrevenue.APPClikeIncome
            }}元
          </div>

          <el-form-item label="点击量:" :label-width="formLabelWidth">
            <template slot-scope="scope">
              <el-col :span="6">
                <el-input
                  v-model="Estimatedrevenue.APPUV"
                  autocomplete="off"
                  style="width: 80%;"
                  @input="CalculateEstimatedRevenue(scope)"
                ></el-input>
              </el-col>
              <el-col
                class="line"
                :span="2"
                style="font-weight: bolder;margin-left: 20px;"
              >
                平均单价:
              </el-col>
              <el-col :span="6">
                <el-input
                  v-model="Estimatedrevenue.APPClikeIncome"
                  autocomplete="off"
                  style="width: 80%;"
                  @input="CalculateEstimatedRevenue(scope)"
                ></el-input>
              </el-col>
            </template>
          </el-form-item>
        </div>
        <div class="calculate_total">
          合计：<span style="color:rgb(0, 60, 255)">{{
            Estimatedrevenue.amountSum
          }}</span>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="CalculateEstimatedrevenueForm = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="handleConsumption">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 计算预估ROI -->
    <el-dialog
      title="计算ROI"
      :visible.sync="CalculateROIForm"
      :close-on-click-modal="false"
    >
      <el-form :model="CalculateROI">
        <template slot-scope="scope">
          <el-form-item label="预估营收" :label-width="formLabelWidth">
            <el-input
              v-model="CalculateROI.Consumption"
              @input="CalculateWantROI(scope)"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="消耗金额" :label-width="formLabelWidth">
            <el-input
              v-model="CalculateROI.Estimatedrevenue"
              autocomplete="off"
              @input="CalculateWantROI"
            ></el-input>
          </el-form-item>
          <el-form-item label="ROI" :label-width="formLabelWidth">
            <el-input v-model="CalculateROI.ROI" autocomplete="off"></el-input>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="CalculateROIForm = false">取 消</el-button>
        <el-button type="primary" @click="CalculateROIForm = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import waves from '@/directive/waves'; // waves directive
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination
import { getAuthChannel, getAuthStatistics } from '@/api/auth';
export default {
  name: 'AuthStatistics',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      total: 0,
      authData: [],
      listQuery: {
        current: 1,
        size: 10,
        startTime: '',
        endTime: '',
        channelId: ''
      },
      formLabelWidth: 100,
      CalculateConsumptionForm: false, // 计算消耗金额表格
      CalculateEstimatedrevenueForm: false, // 计算预估营收表格
      authChanneloptions: [],
      times: [],
      timeNow: [
        new Date(new Date().toLocaleDateString()).getTime(),
        new Date(new Date().toLocaleDateString()).getTime() +
          24 * 60 * 60 * 1000
      ],
      Consumption: {
        insuranceApplyNum: '',
        amount: '',
        amountSum: ''
      }, // 消耗金额
      Estimatedrevenue: {
        insuranceApplyNum: '', // 机构进件量
        AvgIncome: 30, // 平均进件收益
        apsapplyNum: '', // APS推送量
        APSPushIncome: 20, // 单个推送收益
        APPUV: '', // 贷超唯一访问量
        APPClikeIncome: 3, // 单个点击收益
        amountSum: '', // 总金额
        priceAmount: 1
      }, // 预估营收
      CalculateROI: {
        Consumption: '', // 消耗金额
        Estimatedrevenue: '', // 预估营收
        ROI: '' // ROI
      },
      CalculateROIForm: false,
      CalculateConsumArr: [],
      CalculateConsumindex: '',
      EstimatedrevenueArr: [],
      Estimatedindex: [],
      CalculateROIARR: [],
      CalculateROIIndex: ''
    };
  },
  created() {
    this.getAuthChannel();
    this.times = [
      this.timestampToTime(this.timeNow[0]),
      this.timestampToTime(this.timeNow[1])
    ];
    this.listQuery.endTime = this.times[1];
    this.listQuery.startTime = this.times[0];
    this.getAuthStatistics();
  },
  methods: {
    timestampToTime(timestamp) {
      var date = new Date(timestamp);
      var Y = date.getFullYear() + '-';
      var M =
        (date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1) + '-';
      var D =
        (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
      return Y + M + D;
    },
    async getAuthChannel() {
      const res = await getAuthChannel();
      res.data.data.forEach(element => {
        if (element.channel_name !== null) {
          this.authChanneloptions.push(element);
        }
      });
    },
    async getAuthStatistics() {
      if (this.times == null) {
        this.listQuery.endTime = '';
        this.listQuery.startTime = '';
      } else if (this.times.length === 0) {
        this.listQuery.endTime = '';
        this.listQuery.startTime = '';
      } else {
        this.listQuery.endTime = this.times[1];
        this.listQuery.startTime = this.times[0];
      }
      const res = await getAuthStatistics(this.listQuery);
      this.authData = res.data.data.records;
      this.total = res.data.data.total;
      this.CalculateConsumArr = [];
      this.EstimatedrevenueArr = [];
      this.CalculateROIARR = [];
      this.authData.forEach(element => {
        // 进件量*平均进件收益+APS推送量*单个推送收益+贷超唯一访问量*单个点击收益
        element.Estimatedamout =
          element.insuranceApplyNum * this.Estimatedrevenue.AvgIncome +
          element.apsapplyNum * this.Estimatedrevenue.APSPushIncome +
          element.appUV * this.Estimatedrevenue.APPClikeIncome;
        this.EstimatedrevenueArr.push(element.Estimatedamout);
        // 预估营收
        if (element.priceAmount === 1) {
          element.amountSum = (
            element.channelSettlementNum * Number(element.price)
          ).toFixed(3);
        } else {
          element.amountSum = (
            element.Estimatedamout * element.priceAmount
          ).toFixed(3);
        }
        this.CalculateConsumArr.push(element.amountSum);
        element.roi =
          (element.Estimatedamout - element.amountSum) / element.amountSum;
        this.CalculateROIARR.push(element.roi);
      });
    },
    handleFilter() {
      this.listQuery.current = 1;
      if (
        this.listQuery.channelId === undefined ||
        this.listQuery.channelId === ''
      ) {
        this.getAuthStatistics(this.listQuery);
      } else {
        this.authChanneloptions.forEach(element => {
          if (element.authChannelId === this.listQuery.channelId) {
            // this.listQuery.nickname = element.channel_name;
            this.getAuthStatistics(this.listQuery);
          }
        });
      }
      this.getAuthStatistics();
    },
    showCalculateConsumption(scope) {
      this.CalculateTemp = '';
      this.Consumption.amountSum = '';
      const row = scope.row;
      this.CalculateConsumptionForm = true;
      this.Consumption.insuranceApplyNum = row.insuranceApplyNum;
      this.Consumption.amount = 30;
      this.CalculateConsumindex = scope.$index;
      this.Consumption.amountSum = this.CalculateConsumArr[
        this.CalculateConsumindex
      ];
    },
    CalculateConsum(scope) {
      this.Consumption.amountSum =
        this.Consumption.insuranceApplyNum * this.Consumption.amount;
      this.CalculateConsumArr[
        this.CalculateConsumindex
      ] = this.Consumption.amountSum;
      this.$set(
        this.CalculateConsumArr,
        this.CalculateConsumindex,
        this.Consumption.amountSum
      );
    },
    showEstimatedrevenue(scope) {
      const row = scope.row;
      this.Estimatedrevenue.insuranceApplyNum = row.insuranceApplyNum;
      this.Estimatedrevenue.apsapplyNum = row.apsapplyNum;
      this.Estimatedrevenue.APPUV = row.appUV;
      this.Estimatedrevenue.amountSum =
        this.Estimatedrevenue.insuranceApplyNum *
          this.Estimatedrevenue.AvgIncome +
        this.Estimatedrevenue.apsapplyNum *
          this.Estimatedrevenue.APSPushIncome +
        this.Estimatedrevenue.APPUV * this.Estimatedrevenue.APPClikeIncome;
      this.Estimatedrevenue.priceAmount = row.priceAmount;
      this.Estimatedindex = scope.$index;

      this.CalculateEstimatedrevenueForm = true;
    },
    CalculateEstimatedRevenue(scope) {
      this.Estimatedrevenue.amountSum =
        this.Estimatedrevenue.insuranceApplyNum *
          this.Estimatedrevenue.AvgIncome +
        this.Estimatedrevenue.apsapplyNum *
          this.Estimatedrevenue.APSPushIncome +
        this.Estimatedrevenue.APPUV * this.Estimatedrevenue.APPClikeIncome;
      if (this.Estimatedrevenue.priceAmount !== 1) {
        this.CalculateConsumArr[this.Estimatedindex] = (
          this.Estimatedrevenue.amountSum * this.Estimatedrevenue.priceAmount
        ).toFixed(3);
      }

      this.$set(
        this.EstimatedrevenueArr,
        this.Estimatedindex,
        this.Estimatedrevenue.amountSum,
        this.CalculateConsumArr
      );
    },
    handleConsumption() {
      // this.CalculateConsumArr[this.Estimatedindex] =
      //   this.Estimatedrevenue.amountSum * 0.7;
      // this.$set(this.CalculateConsumArr);
      // console.log(this.CalculateConsumArr);
      this.CalculateEstimatedrevenueForm = false;
    },
    showCalculateROI(scope) {
      this.CalculateROIForm = true;
      this.CalculateROI.Consumption = this.CalculateConsumArr[scope.$index];
      this.CalculateROI.Estimatedrevenue = this.EstimatedrevenueArr[
        scope.$index
      ];
      this.CalculateROI.ROI = this.CalculateROIARR[scope.$index];
      this.CalculateROIIndex = scope.$index;
    }, // 计算ROI
    CalculateWantROI(scope) {
      this.CalculateROI.ROI =
        (this.CalculateROI.Estimatedrevenue - this.CalculateROI.Consumption) /
        this.CalculateROI.Consumption;
      this.$set(
        this.CalculateROIARR,
        this.CalculateROIIndex,
        this.CalculateROI.ROI
      );
    },
    // 四舍五入
    roundNumber(number, decimalPlaces) {
      return Number(number).toFixed(decimalPlaces);
    }
  }
};
</script>
<style>
.demo-input-suffix {
  width: 800px;
  height: 100px;
}
.Calculate_name {
  margin-bottom: 20px;
  font-size: 14px;
  font-weight: bold;
}
.calculate_total {
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
}
</style>
